package cn.edu.zut.hhr.controller;


import cn.edu.zut.hhr.annotation.LogAnnotation;
import cn.edu.zut.hhr.entity.User;
import cn.edu.zut.hhr.service.LoginService;
import cn.edu.zut.hhr.service.UserService;
import cn.edu.zut.hhr.utils.JwtUtil;
import cn.edu.zut.hhr.utils.MD5Util;
import cn.edu.zut.hhr.utils.RedisUtil;
import cn.edu.zut.hhr.utils.UserUtil;
import cn.edu.zut.hhr.vo.RestResponse;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.*;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * <p>
 * 标签表 前端控制器
 * </p>
 *
 * @author HHR
 * @since 2021-08-21
 */
@RestController
@RequestMapping("/user")
@Api(value = "用户操作相关接口")
public class UserController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserService userService;
    @Resource
    private LoginService loginService;

    /**
     * emm,因为service层设计不合理(即service层不进行包装),这里很难用service层进行处理了...直接写controller了
     *
     * @param token
     * @return
     */
    @ApiOperation("根据token获取当前用户")

    @ApiResponses(value = {@ApiResponse(code = 200, message = "success"), @ApiResponse(code = 401, message = "用户登录过期")})
    @GetMapping({"/", ""})
    @LogAnnotation(module = "用户", operator = "获取当前用户")
    @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "String", paramType = "path")
    public RestResponse getUserByToken(@RequestHeader("token") String token) {
        String username = null;
        try {
            username = (String) JwtUtil.verifyToken(token).get("username");
            User user = JSON.parseObject(redisUtil.get("username_" + username).toString(), User.class);
            if (user != null) {
                return RestResponse.success(user);
            }
        } catch (ClassCastException e) {
            e.printStackTrace();
        }
        return RestResponse.fail(401, "用户信息已过期,请重写登录");
    }

    @PostMapping({"/", ""})
    @LogAnnotation(module = "用户", operator = "注册")
    public RestResponse registerUser(@ApiParam(value = "用户", required = true, type = "User") @RequestBody User user) {
        return userService.registerUser(user);
    }

    @PostMapping("/update/passwd")
    @ApiOperation("修改密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "new_passwd", value = "新密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "old_passwd", value = "原始密码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "repeat_passwd", value = "重复密码", required = true, dataType = "String")
    })
    public RestResponse updatePasswd(@RequestParam("new_passwd") String newPasswd,
                                     @RequestParam("old_passwd") String oldPasswd,
                                     @RequestParam("repeat_passwd") String repeatPasswd) {
        User user = UserUtil.currentUser();
        if (!oldPasswd.equals(repeatPasswd)) {
            return RestResponse.fail(HttpStatus.BAD_GATEWAY.value(), "old passwd must equals repeat passwd");
        }
        oldPasswd = MD5Util.encrypt(oldPasswd);
        if (!oldPasswd.equals(user.getPassword())) {
            return RestResponse.fail(HttpStatus.BAD_GATEWAY.value(), "old passwd err");
        }
        boolean ok = userService.updatePasswd(user, newPasswd);
        if (!ok) {
            return RestResponse.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "update passwd err");
        }
        //修改redis缓存过期
        String token = loginService.login(user.getId(), newPasswd);
        return RestResponse.success(token);
    }

    @PostMapping("/update")
    @ApiOperation("修改除passwd外的其余用户内容")
    @ApiImplicitParams({
            @ApiImplicitParam(name="user",value = "用户",required = true,dataType = "User")
    })
    public RestResponse update(@RequestBody User user){
        User currentUser = UserUtil.currentUser();
        user.setPassword(currentUser.getPassword());
        boolean ok = userService.updateById(user);
        if(!ok){
            return RestResponse.fail(HttpStatus.INTERNAL_SERVER_ERROR.value(),"update err");
        }
        user.setPassword("");
        return RestResponse.success(user);
    }
}
